﻿// EbkSearch.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include "MainWnd.h"


#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream> 
#include <algorithm>
#include <Windows.h>
#include <Shlobj.h>
using namespace std;




bool sortResult(const RESULT_DATA& a, const RESULT_DATA& b)
{
	return a.vModule.size() >= b.vModule.size();
}


void listEbkFiles(const string sPath,vector<string>& fileList)
{
	HANDLE hFind;
	WIN32_FIND_DATA findData;
	LARGE_INTEGER size;

	string sDir =sPath + "*.*";
	hFind = FindFirstFile(sDir.c_str(), &findData);
	if (hFind == INVALID_HANDLE_VALUE)
	{
		cout << "Error:Failed to find first file!\n";
		return;
	}
	do
	{
		// 忽略"."和".."两个结果 
		if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0)
			continue;
		if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)    // 是否是目录 
		{
			//cout << findData.cFileName << "\t<dir>\n";
		}
		else
		{
			size.LowPart = findData.nFileSizeLow;
			size.HighPart = findData.nFileSizeHigh;
			string sFile = sPath+findData.cFileName;
			if (sFile.find(".ebk") != string::npos || sFile.find(".EBK") != string::npos)
			{
				cout << findData.cFileName << "\t" << size.QuadPart << " bytes\n";
				fileList.push_back(sFile);
			}
		}
	} while (FindNextFile(hFind, &findData));
}

int main1()
{
	string sPath;
#if 1
	TCHAR szBuffer[MAX_PATH] = { 0 };
	TCHAR szPath[MAX_PATH] = { 0 };

	BROWSEINFO bi;
	ZeroMemory(&bi, sizeof(BROWSEINFO));
	bi.hwndOwner = NULL;
	bi.pszDisplayName = szBuffer;
	bi.lpszTitle ="请选择文件夹:";
	bi.ulFlags = BIF_BROWSEINCLUDEFILES;
	LPITEMIDLIST idl = SHBrowseForFolder(&bi);
	if (NULL == idl)
	{
		return -1;
	}
	SHGetPathFromIDList(idl, szPath);
	
	sPath = szPath;


	WIN32_FIND_DATAA FindFileData;
	FindFirstFile(szPath, &FindFileData);
	if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
	{
		sPath += "\\";
	}
	else
	{
		int iPos = sPath.find_last_of("\\");
		sPath = sPath.substr(0, iPos + 1);	
	}
#else
	sPath = R"(C:\Users\Kee\Desktop\新建文件夹\)";
#endif // 0

	
	vector<_RESULT_DATA> resultList;
	vector<string> fileList;
	listEbkFiles(sPath.c_str(), fileList);
	if (fileList.empty())
	{
		cout << "Erorr:\""<<sPath << "\"" << "目录底下没有找到 *.ebk文件" << endl;
		goto done;
	}
	for (size_t i = 0; i < fileList.size(); i++)
	{
		int iPosS = fileList[i].find_last_of("\\") +1;
		int iPosE = fileList[i].find_last_of(".");
		string sModule = fileList[i].substr(iPosS, iPosE - iPosS);
		ifstream ebkfile(fileList[i]);
		string sNumber;
		if (!ebkfile.is_open())
		{
			cout << "Erorr:\"" << fileList[i] << "\"" << "文件未成功打开" << endl;
			goto done;
		}
		
		while (getline(ebkfile, sNumber))
		{
			RESULT_DATA resultData;
			BOOL bMatched = false;
			if (sNumber.empty())
				continue;

			if (resultList.empty())
			{
				resultData.sNumber = sNumber;
				resultData.vModule.push_back(sModule);
				resultList.push_back(resultData);
				continue;
			}
			for (size_t j = 0; j < resultList.size(); j++)
			{
				if (resultList[j].sNumber == sNumber)
				{
					resultList[j].vModule.push_back(sModule);
					bMatched = true;
					break;
				}
			}
			if (!bMatched)
			{
				resultData.sNumber = sNumber;
				resultData.vModule.push_back(sModule);
				resultList.push_back(resultData);
			}
			
		}
		ebkfile.close();

	}

	if (!resultList.empty())
	{
		string sOutput = sPath + "Result.csv";
		ofstream outputFile(sOutput);
		if (!outputFile.is_open())
		{
			cout << "Error:创建输出文件失败" << endl;
			goto done;
		}
		sort(resultList.begin(), resultList.end(), sortResult);

		for (size_t i = 0; i < resultList.size(); i++)
		{
			RESULT_DATA resultData = resultList[i];
			stringstream ssBuilder;
			if (resultData.vModule.size() < 2)
				continue;
			resultData.sNumber = resultData.sNumber.substr(1);
			ssBuilder << resultData.sNumber << ",";
			ssBuilder << "(" << resultData.vModule.size() << " 板块)";
			for (size_t j = 0; j < resultData.vModule.size(); j++)
			{
				ssBuilder << "," << resultData.vModule[j] ;
			}
			ssBuilder << endl;
			outputFile << ssBuilder.str();
		}
		outputFile.close();
		
		cout << "结果已经生成："<< sOutput << endl;
		cout << "正在打开结果文件..." << endl;
		ShellExecute(NULL, "open", "explorer.exe", sOutput.c_str(), NULL, SW_SHOWNORMAL);
		//return 0;
	}

done:
	system("pause");
	return 0;
}


void InitResource()
{
	// 资源类型
#ifdef _DEBUG
	CPaintManagerUI::SetResourceType(UILIB_FILE);
#else
	CPaintManagerUI::SetResourceType(UILIB_RESOURCE);
#endif
	// 资源路径
	CDuiString strResourcePath = CPaintManagerUI::GetInstancePath();
	// 加载资源
	switch (CPaintManagerUI::GetResourceType())
	{
	case UILIB_FILE:
	{
		strResourcePath += _T("res\\");
		CPaintManagerUI::SetResourcePath(strResourcePath.GetData());
		// 加载资源管理器
		//CResourceManager::GetInstance()->LoadResource(_T("res.xml"), NULL);
		break;
	}
	case UILIB_RESOURCE:
	{
		strResourcePath += _T("res\\");
		CPaintManagerUI::SetResourcePath(strResourcePath.GetData());
		// 加载资源管理器
		//CResourceManager::GetInstance()->LoadResource(_T("IDR_RES"), _T("xml"));
		break;
	}
	case UILIB_ZIP:
	{
		strResourcePath += _T("skin\\");
		CPaintManagerUI::SetResourcePath(strResourcePath.GetData());
		// 加密
		CPaintManagerUI::SetResourceZip(_T("duidemo_pwd.zip"), true, _T("duilib_ultimate"));
		//CPaintManagerUI::SetResourceZip(_T("duidemo.zip"), true);
		// 加载资源管理器
		CResourceManager::GetInstance()->LoadResource(_T("res.xml"), NULL);
		break;
	}
	case UILIB_ZIPRESOURCE:
	{
		strResourcePath += _T("skin\\duidemo\\");
		CPaintManagerUI::SetResourcePath(strResourcePath.GetData());
		HRSRC hResource = ::FindResource(CPaintManagerUI::GetResourceDll(), _T("IDR_ZIPRES"), _T("ZIPRES"));
		if (hResource != NULL) {
			DWORD dwSize = 0;
			HGLOBAL hGlobal = ::LoadResource(CPaintManagerUI::GetResourceDll(), hResource);
			if (hGlobal != NULL) {
				dwSize = ::SizeofResource(CPaintManagerUI::GetResourceDll(), hResource);
				if (dwSize > 0) {
					CPaintManagerUI::SetResourceZip((LPBYTE)::LockResource(hGlobal), dwSize);
					// 加载资源管理器
					CResourceManager::GetInstance()->LoadResource(_T("res.xml"), NULL);
				}
			}
			::FreeResource(hResource);
		}
	}
	break;
	}

}

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int nCmdShow)
{
	//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	//_CrtDumpMemoryLeaks();
	// COM
	HRESULT Hr = ::CoInitialize(NULL);
	if (FAILED(Hr)) return 0;
	// OLE
	HRESULT hRes = ::OleInitialize(NULL);
	// 初始化UI管理器
	CPaintManagerUI::SetInstance(hInstance);
	// 初始化资源
	InitResource();

	// 创建主窗口
	CMainWnd* pMainWnd = new CMainWnd();
	if (pMainWnd == NULL) return 0;
	pMainWnd->Create(NULL, _T("EbkTool"), UI_WNDSTYLE_FRAME, 0L, 0, 0, 800, 572);
	pMainWnd->CenterWindow();
	// 消息循环
	CPaintManagerUI::MessageLoop();
	// 销毁窗口
	delete pMainWnd;
	pMainWnd = NULL;
	// 清理资源
	CPaintManagerUI::Term();
	// OLE
	OleUninitialize();
	// COM
	::CoUninitialize();

	return 0;
}